<script setup lang="ts">
import { h, onMounted, ref, watch } from 'vue';
import type {
  DataTableColumns,
  DrawerPlacement,
  FormInst,
  FormRules,
  UploadCustomRequestOptions,
  UploadFileInfo
} from 'naive-ui';
import { NButton, NImage, useDialog, useMessage } from 'naive-ui';
import {
  commonImageFile,
  deleteUser,
  getUserInfoList,
  insertUserInfo,
  msgCheckAction,
  updateUserInfo
} from '@/service/api';
import { localStg } from '@/utils/storage';

const pageCount = ref<number>();

const memberForm = ref({
  id: undefined,
  position: undefined,
  name: undefined,
  age: undefined,
  birthTime: undefined,
  workYear: undefined,
  workUnitTime: undefined,
  colleges: undefined,
  major: undefined,
  education: undefined,
  employCertCode: undefined,
  diploma: undefined,
  diplomaCode: undefined,
  identityPicName: undefined, // 身份证图片名称
  identityPicPath: undefined, // 身份证图片地址
  diplomaPicName: undefined, // 毕业证书图片名称
  diplomaPicPath: undefined, // 毕业证书图片地址
  certificatePicName: undefined, // 资质证书图片名称
  certificatePicPath: undefined, // 资质证书图片地址
  socialPicName: undefined, // 社保证明图片名称
  socialPicPath: undefined, // 社保证明图片地址
  employCertPicName: undefined, // 劳动合同图片名称
  employCertPicPath: undefined, // 劳动合同图片地址
  identityBakPicName: undefined, // 身份证背面图片名称
  identityBakPicPath: undefined // 身份证背面图片地址
});

const idFrontImage = ref<UploadFileInfo[]>([]);
const idBackImage = ref<UploadFileInfo[]>([]);
const diplomaImage = ref<UploadFileInfo[]>([]);
const certificateImage = ref<UploadFileInfo[]>([]);
const socialImage = ref<UploadFileInfo[]>([]);
const employImage = ref<UploadFileInfo[]>([]);

const message = useMessage();

const memberFormRef = ref<HTMLElement & FormInst>();

const memberRules: FormRules = {
  position: {
    required: true,
    message: '请输入职位',
    trigger: 'blur'
  },
  name: {
    required: true,
    message: '请输入姓名',
    trigger: 'blur'
  },
  age: {
    required: true,
    message: '请输入年龄',
    trigger: 'input',
    type: 'number'
  },
  workYear: {
    required: true,
    message: '请输入工作年限',
    trigger: 'input',
    type: 'number'
  },
  workUnitTime: {
    required: true,
    message: '请输入工作时间',
    trigger: 'input'
  },
  employCertCode: {
    required: true,
    message: '请输入劳动合同编号',
    trigger: 'blur'
  },
  education: {
    required: true,
    message: '请输入学历',
    trigger: 'blur'
  }
};

const active = ref(false);

const placement = ref<DrawerPlacement>('right');

// 新建
const activate = (place: DrawerPlacement) => {
  active.value = true;
  memberForm.value = {
    id: undefined,
    position: undefined,
    name: undefined,
    age: undefined,
    birthTime: undefined,
    workYear: undefined,
    workUnitTime: undefined,
    colleges: undefined,
    major: undefined,
    education: undefined,
    employCertCode: undefined,
    diploma: undefined,
    diplomaCode: undefined,
    identityPicName: undefined, // 身份证图片名称
    identityPicPath: undefined, // 身份证图片地址
    diplomaPicName: undefined, // 毕业证书图片名称
    diplomaPicPath: undefined, // 毕业证书图片地址
    certificatePicName: undefined, // 资质证书图片名称
    certificatePicPath: undefined, // 资质证书图片地址
    socialPicName: undefined, // 社保证明图片名称
    socialPicPath: undefined, // 社保证明图片地址
    employCertPicName: undefined, // 劳动合同图片名称
    employCertPicPath: undefined, // 劳动合同图片地址
    identityBakPicName: undefined, // 身份证背面图片名称
    identityBakPicPath: undefined // 身份证背面图片地址
  };
  idFrontImage.value = [];
  idBackImage.value = [];
  diplomaImage.value = [];
  certificateImage.value = [];
  socialImage.value = [];
  employImage.value = [];
  placement.value = place;
};

const emit = defineEmits(['refresh']);

const props = defineProps({
  fileData: {
    type: Array,
    default: () => []
  },
  thirdParentId: {
    type: Number,
    default: 0
  }
});

watch(
  () => props.thirdParentId,
  newValue => {
    if (newValue) {
      getList();
    }
  }
);

const { VITE_OTHER_SERVICE_BASE_URL } = import.meta.env;

const otherUrl: any = JSON.parse(VITE_OTHER_SERVICE_BASE_URL);

const imgUrl: any = otherUrl.imgUrl;

const fileList = ref([]);

const dialog = useDialog();

// 确定点击提交事件
async function handleSubmitMember() {
  await memberFormRef.value?.validate(async errors => {
    if (!errors) {
      const checkParams: any = {
        moduleValue: localStg.get('moduleId') || 1,
        keyword: `${memberForm.value.name},${memberForm.value.position},${memberForm.value.employCertCode},${memberForm.value.colleges},${memberForm.value.major},${memberForm.value.education},${memberForm.value.diploma},${memberForm.value.diplomaCode}`
      };

      const { data: checkData, error: checkError } = await msgCheckAction(checkParams);
      if (!checkError) {
        if (checkData && checkData.length > 0) {
          dialog.error({
            title: '温馨提示',
            content: `人员信息中包含以下敏感词：\n${checkData.join('，')}`,
            style: 'white-space: pre-line;',
            positiveText: '确认'
          });
          return;
        }
      }

      const tmp = { ...memberForm.value, folderId: props.thirdParentId };
      console.log(tmp);
      const api = tmp.id ? updateUserInfo : insertUserInfo;
      const { data, error } = await api(tmp);
      if (!error) {
        active.value = false;
        window.$message?.success('操作成功');
        getList();
      }
    }
  });
}

function closeDrawer() {
  fileList.value = [];
}

const tableLoading = ref(false);

const dataList = ref([]);

const formData = ref({
  pageNum: 1,
  pageSize: 10
});

// 获取人员信息
async function getList() {
  tableLoading.value = true;
  const { data, error } = await getUserInfoList({
    ...formData.value,
    folderId: props.thirdParentId
  });
  if (!error) {
    dataList.value = data?.list;
    pageCount.value = data?.pages;
    tableLoading.value = false;
  }
}

function handleDelete(item: any) {
  dialog.warning({
    title: '删除人员',
    content: '请问是否确认删除该人员？',
    positiveText: '确定',
    negativeText: '返回',
    onPositiveClick: async () => {
      const { data, error } = await deleteUser({ ids: item.id });
      if (!error) {
        message.success('已删除');
        await getList();
      }
    },
    onNegativeClick: () => {
      message.warning('已取消');
    }
  });
}

// 编辑
function handleEdit(row: any) {
  active.value = true;
  idFrontImage.value = [];
  idBackImage.value = [];
  diplomaImage.value = [];
  certificateImage.value = [];
  socialImage.value = [];
  employImage.value = [];
  memberForm.value = JSON.parse(JSON.stringify(row));
  if (memberForm.value.identityPicPath) {
    const picData = {
      id: memberForm.value.id,
      name: memberForm.value.identityPicName,
      status: 'finished',
      url: imgUrl + memberForm.value.identityPicPath
    };
    idFrontImage.value.push(picData);
  }
  if (memberForm.value.diplomaPicPath) {
    const picData = {
      id: memberForm.value.id,
      name: memberForm.value.diplomaPicName,
      status: 'finished',
      url: imgUrl + memberForm.value.diplomaPicPath
    };
    diplomaImage.value.push(picData);
  }
  if (memberForm.value.identityBakPicPath) {
    const picData = {
      id: memberForm.value.id,
      name: memberForm.value.identityBakPicName,
      status: 'finished',
      url: imgUrl + memberForm.value.identityBakPicPath
    };
    idBackImage.value.push(picData);
  }
  if (memberForm.value.socialPicPath) {
    const picData = {
      id: memberForm.value.id,
      name: memberForm.value.socialPicName,
      status: 'finished',
      url: imgUrl + memberForm.value.socialPicPath
    };
    socialImage.value.push(picData);
  }
  if (memberForm.value.employCertPicPath) {
    const picData = {
      id: memberForm.value.id,
      name: memberForm.value.employCertPicName,
      status: 'finished',
      url: imgUrl + memberForm.value.employCertPicPath
    };
    employImage.value.push(picData);
  }
  if (memberForm.value.certificatePicPath) {
    const picData = {
      id: memberForm.value.id,
      name: memberForm.value.certificatePicName,
      status: 'finished',
      url: imgUrl + memberForm.value.certificatePicPath
    };
    certificateImage.value.push(picData);
  }
}
// 删除图片
function removeImgClick(
  options: {
    file: UploadFileInfo;
    fileList: Array<UploadFileInfo>;
  },
  name: any,
  path: any
) {
  fileList.value = [];
  memberForm.value[name] = undefined;
  memberForm.value[path] = undefined;
  console.log(memberForm.value);
}

// 自定义上传图片
const customImageRequest = async ({ file, onFinish }: UploadCustomRequestOptions, name: any, path: any) => {
  console.log(file);
  const formData = new FormData();
  if (file.status == 'pending') {
    formData.append('uploadFiles', file.file as Blob);
  }
  const { data, error } = await commonImageFile(formData);
  if (!error) {
    console.log(data[0]);
    memberForm.value[name] = data[0].fileCname;
    memberForm.value[path] = data[0].filePath;
    onFinish();
    console.log(memberForm.value);
  }
};

onMounted(() => {
  getList();
});

function createColumns(): DataTableColumns {
  return [
    {
      title: '序号',
      align: 'center',
      key: 'key',
      render: (_, index) => {
        return `${(formData.value.pageNum - 1) * formData.value.pageSize + index + 1}`;
      },
      width: '80px'
    },
    {
      title: '姓名',
      key: 'name',
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: '职位',
      key: 'position',
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: '工作年限',
      key: 'workYear',
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: '参与本单位工作时间',
      key: 'workUnitTime',
      align: 'center',
      ellipsis: {
        tooltip: true
      },
      width: '180px'
    },
    {
      title: '劳动合同编号',
      key: 'employCertCode',
      align: 'center',
      ellipsis: {
        tooltip: true
      },
      width: '150px'
    },
    {
      title: '年龄',
      key: 'age',
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: '学历',
      key: 'education',
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: '身份证正面',
      key: 'identityPicPath',
      align: 'center',
      render(row: any) {
        return [
          h(NImage, {
            width: 50,
            src: imgUrl + row.identityPicPath
          })
        ];
      }
    },
    {
      title: '身份证背面',
      key: 'identityBakPicPath',
      align: 'center',
      render(row: any) {
        return [
          h(NImage, {
            width: 50,
            src: imgUrl + row.identityBakPicPath
          })
        ];
      }
    },
    {
      title: '毕业证书',
      key: 'diplomaPicPath',
      align: 'center',
      render(row: any) {
        return [
          h(NImage, {
            width: 50,
            src: imgUrl + row.diplomaPicPath
          })
        ];
      }
    },
    {
      title: '资质证书',
      key: 'certificatePicPath',
      align: 'center',
      render(row: any) {
        return [
          h(NImage, {
            width: 50,
            src: imgUrl + row.certificatePicPath
          })
        ];
      }
    },
    {
      title: '社保证明',
      key: 'socialPicPath',
      align: 'center',
      render(row: any) {
        return [
          h(NImage, {
            width: 50,
            src: imgUrl + row.socialPicPath
          })
        ];
      }
    },
    {
      title: '劳动合同',
      key: 'employCertPicPath',
      align: 'center',
      render(row: any) {
        return [
          h(NImage, {
            width: 50,
            src: imgUrl + row.employCertPicPath
          })
        ];
      }
    },
    {
      title: '操作',
      key: 'actions',
      align: 'center',
      width: '180',
      fixed: 'right',
      render(row: any) {
        return [
          h(
            NButton,
            {
              type: 'info',
              strong: true,
              tertiary: true,
              style: 'margin-right:10px',
              onClick: () => handleEdit(row)
            },
            { default: () => '编辑' }
          ),
          h(
            NButton,
            {
              type: 'error',
              strong: true,
              tertiary: true,
              onClick: () => handleDelete(row)
            },
            { default: () => '删除' }
          )
        ];
      }
    }
  ];
}
const columns: any = createColumns();
</script>

<template>
  <div class="w-full">
    <!-- 新增人员 -->
    <img
      class="upload"
      src="@/assets/bid-materials/addMember.png"
      alt=""
      style="width: 120px"
      @click="activate('right')"
    />
    <div class="table-area">
      <NDataTable
        striped
        size="small"
        :loading="tableLoading"
        :columns="columns"
        :data="dataList"
        :bordered="false"
        :max-height="600"
        :scroll-x="1800"
        style="font-size: 15px; color: #666666"
      />
      <NPagination
        v-model:page="formData.pageNum"
        v-model:page-size="formData.pageSize"
        size="small"
        style="float: right; position: absolute; top: 810px; right: 80px"
        :page-count="pageCount"
        @update:page="getList"
      />
    </div>
  </div>
  <NDrawer v-model:show="active" :width="800" :placement="placement" :mask-closable="false">
    <NDrawerContent title="人员信息" closable>
      <template #header>人员信息</template>
      <NForm
        ref="memberFormRef"
        :model="memberForm"
        :rules="memberRules"
        require-mark-placement="left"
        label-placement="left"
      >
        <NGrid :cols="24" :x-gap="24">
          <NFormItemGi :span="20" label="职位" path="position" :label-width="160">
            <NInput v-model:value="memberForm.position" placeholder="请输入" />
          </NFormItemGi>
          <NFormItemGi :span="12" label="姓名" path="name" :label-width="160">
            <NInput v-model:value="memberForm.name" placeholder="请输入" />
          </NFormItemGi>
          <NFormItemGi :span="8" label="年龄" path="age">
            <NInputNumber v-model:value="memberForm.age" clearable />
          </NFormItemGi>
          <NFormItemGi :span="20" label="出生年月" path="birthTime" :label-width="160">
            <NDatePicker
              v-model:formatted-value="memberForm.birthTime"
              style="width: 280px"
              value-format="yyyy-MM-dd"
              type="date"
              :is-date-disabled="
                (ts: number) => {
                  return ts > Date.now();
                }
              "
              clearable
            />
          </NFormItemGi>
          <NFormItemGi :span="20" label="工作年限" path="workYear" :label-width="160">
            <NInputNumber v-model:value="memberForm.workYear" style="width: 280px" clearable />
          </NFormItemGi>
          <NFormItemGi :span="20" label="参加本单位工作时间" path="workUnitTime" :label-width="160">
            <NDatePicker
              v-model:formatted-value="memberForm.workUnitTime"
              style="width: 280px"
              :is-date-disabled="
                (ts: number) => {
                  return ts > Date.now();
                }
              "
              value-format="yyyy-MM-dd"
              type="date"
              clearable
            />
          </NFormItemGi>
          <NFormItemGi :span="20" label="劳动合同编号" path="employCertCode" :label-width="160">
            <NInput v-model:value="memberForm.employCertCode" placeholder="请输入" />
          </NFormItemGi>
          <NFormItemGi :span="12" label="院校" path="colleges" :label-width="160">
            <NInput v-model:value="memberForm.colleges" placeholder="请输入" />
          </NFormItemGi>
          <NFormItemGi :span="8" label="专业" path="major">
            <NInput v-model:value="memberForm.major" placeholder="请输入" />
          </NFormItemGi>
          <NFormItemGi :span="20" label="学历" path="education" :label-width="160">
            <NInput v-model:value="memberForm.education" placeholder="请输入" />
          </NFormItemGi>
          <NFormItemGi :span="12" label="毕业证书" path="diploma" :label-width="160">
            <NInput v-model:value="memberForm.diploma" placeholder="请输入" />
          </NFormItemGi>
          <NFormItemGi :span="8" label="证书编号" path="diplomaCode">
            <NInput v-model:value="memberForm.diplomaCode" placeholder="请输入" />
          </NFormItemGi>
          <NFormItemGi :span="22" label="附件上传" path="textareaValue" :label-width="160">
            <NUpload
              accept=".jpg, .png"
              :multiple="false"
              :default-file-list="idFrontImage"
              list-type="image-card"
              :max="1"
              :custom-request="
                $event => {
                  customImageRequest($event, 'identityPicName', 'identityPicPath');
                }
              "
              @remove="
                $event => {
                  removeImgClick($event, 'identityPicName', 'identityPicPath');
                }
              "
            >
              <span>身份证正面</span>
            </NUpload>
            <NUpload
              accept=".jpg, .png"
              :multiple="false"
              :default-file-list="idBackImage"
              list-type="image-card"
              :max="1"
              :custom-request="
                $event => {
                  customImageRequest($event, 'identityBakPicName', 'identityBakPicPath');
                }
              "
              @remove="
                $event => {
                  removeImgClick($event, 'identityBakPicName', 'identityBakPicPath');
                }
              "
            >
              <span>身份证背面</span>
            </NUpload>
            <NUpload
              accept=".jpg, .png"
              :multiple="false"
              :default-file-list="diplomaImage"
              list-type="image-card"
              :max="1"
              :custom-request="
                $event => {
                  customImageRequest($event, 'diplomaPicName', 'diplomaPicPath');
                }
              "
              @remove="
                $event => {
                  removeImgClick($event, 'diplomaPicName', 'diplomaPicPath');
                }
              "
            >
              <span>毕业证书</span>
            </NUpload>
          </NFormItemGi>
          <NFormItemGi :span="17" :offset="5" label="" path="textareaValue" :label-width="160">
            <NUpload
              accept=".jpg, .png"
              :multiple="false"
              :default-file-list="certificateImage"
              list-type="image-card"
              :max="1"
              :custom-request="
                $event => {
                  customImageRequest($event, 'certificatePicName', 'certificatePicPath');
                }
              "
              @remove="
                $event => {
                  removeImgClick($event, 'certificatePicName', 'certificatePicPath');
                }
              "
            >
              <span>资质证书</span>
            </NUpload>
            <NUpload
              accept=".jpg, .png"
              :multiple="false"
              :default-file-list="socialImage"
              list-type="image-card"
              :max="1"
              :custom-request="
                $event => {
                  customImageRequest($event, 'socialPicName', 'socialPicPath');
                }
              "
              @remove="
                $event => {
                  removeImgClick($event, 'socialPicName', 'socialPicPath');
                }
              "
            >
              <span>社保证明</span>
            </NUpload>
            <NUpload
              accept=".jpg, .png"
              :multiple="false"
              :default-file-list="employImage"
              list-type="image-card"
              :max="1"
              :custom-request="
                $event => {
                  customImageRequest($event, 'employCertPicName', 'employCertPicPath');
                }
              "
              @remove="
                $event => {
                  removeImgClick($event, 'employCertPicName', 'employCertPicPath');
                }
              "
            >
              <span>劳动合同</span>
            </NUpload>
          </NFormItemGi>
        </NGrid>
      </NForm>
      <template #footer>
        <NButton style="width: 110px; height: 40px; margin-right: 20px" @click="() => (active = false)">取 消</NButton>
        <NButton type="primary" style="width: 110px; height: 40px" @click="handleSubmitMember">确 定</NButton>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped lang="scss">
.table-area {
  margin-top: 15px;
  margin-left: 35px;
  width: 1485px;
  height: 400px;
  :deep(.n-data-table .n-data-table-th) {
    background-color: #f2f0ff;
    height: 60px;
    color: #333333;
    font-size: 18px;
  }
}
.upload {
  float: right;
  margin-bottom: 15px;
  margin-right: 79px;
  &:hover {
    cursor: pointer;
  }
}
</style>
